<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Croakd Installation
 */
class Install_Controller extends Core_Controller {

  public $perms_errors = array();

  public function index() {
  
    if ($this->_is_installed() === TRUE) {
      url::redirect('install/success');
    }
  
    if ($_POST) {
      $post = $this->input->post();
      if ($this->_install_app($post) === TRUE) {
        url::redirect('install/success');
      }
    }
    
    $this->_check_perms();
  
		$this->view = new View('install');
		$this->view->perm_errors = $this->perms_errors;
		$this->view->render(TRUE);
  }
  
  public function success()
  {
    if ($this->_is_installed() === FALSE) {
      url::redirect('install');
    }
  
  	$this->view = new View('installed');
		$this->view->render(TRUE);
  }
  
  private function _is_installed()
  {
    // Looking for database file
    if (!file_exists(APPPATH . "config/database.php")) {
      return FALSE;
    }
    
    if (Kohana::config('database.default.connection.database') == 'kohana') {
      return FALSE;
    }
    
    return TRUE;
  }
  
  private function _check_perms()
  {
    if (!file_exists(MODPATH . 'install/sql/croakd.sql')) {
      array_push($this->perms_errors, array('error' => 'Doesn\'t not exists database file'));
    }
    
    if (!is_writable(APPPATH . "config/")) {
     array_push($this->perms_errors, array('error' => 'The directory : <strong>application/config/</strong> must be writable'));
    }
    else {
      touch(APPPATH . "config/database.php");
      if (!is_writable(APPPATH . "config/database.php")) {
       array_push($this->perms_errors, array('error' => 'The file : <strong>application/config/database.php</strong> is not writable (0666 permission required at least)'));
      }
    }
  }
  
  private function _install_app($data = NULL) 
  {
    $link = @mysql_connect($data['db-host'], $data['db-user'], $data['db-pass']);
    if (!$link) {
      mysql_close($link);
      return FALSE;
    }
    mysql_select_db($data['db-name'], $link);
    
    // Dump the database
    $croakd = MODPATH . 'install/sql/croakd.sql';
    $this->_import_sql($croakd);
    
    // Create the config/database file
    $db_file     = APPPATH . "config/database.php";
    $fh          = fopen($db_file, 'w+') or die("Can't open file");
    $config_data = "<?php defined('SYSPATH') OR die('No direct access allowed.');
  \$config['default'] = array
  (
	  'benchmark'     => TRUE,
	  'persistent'    => FALSE,
	  'connection'    => array
	  (
		  'type'     => 'mysql',
		  'user'     => '". $data['db-user'] ."',
		  'pass'     => '". $data['db-pass'] ."',
		  'host'     => '". $data['db-host'] ."',
		  'port'     => FALSE,
		  'socket'   => FALSE,
		  'database' => '". $data['db-name'] ."'
	  ),
	  'character_set' => 'utf8',
	  'table_prefix'  => 'ckd_',
	  'object'        => TRUE,
	  'cache'         => FALSE,
	  'escape'        => TRUE
  );";
    fwrite($fh, $config_data);
    fclose($fh);
    chmod( $db_file , 0777 );
    
    // Admin user
    $admin_data = array(
      'email'       => $data['ckd-email'],
      'name'        => 'croakd admin',
      'username'    => $data['ckd-user'],
      'password'    => $data['ckd-pass'],
      'logins'      => 0,
      'created_at'  => date('Y-m-d H:i:s'),
    );
    
    $user = ORM::factory('user');
    $user_id = $user->create($admin_data);
    
    $user = ORM::factory('user', $user_id);
    $user->add(ORM::factory('role', 'admin'));
    
    return TRUE;
  }
  
  private function _import_sql($filename)
  {
	  $return = false;
	  $sql_start = array('INSERT', 'UPDATE', 'DELETE', 'DROP', 'GRANT', 'REVOKE', 'CREATE', 'ALTER');
	  $sql_run_last = array('INSERT');

	  if (file_exists($filename)) {
		  $lines = file($filename);
		  $queries = array();
		  $query = '';

		  if (is_array($lines)) {
			  foreach ($lines as $line) {
				  $line = trim($line);

				  if(!preg_match("'^--'", $line)) {
					  if (!trim($line)) {
						  if ($query != '') {
							  $first_word = trim(strtoupper(substr($query, 0, strpos($query, ' '))));
							  if (in_array($first_word, $sql_start)) {
								  $pos = strpos($query, '`')+1;
								  $query = substr($query, 0, $pos) . substr($query, $pos);
							  }

							  $priority = 1;
							  if (in_array($first_word, $sql_run_last)) {
								  $priority = 10;
							  } 

							  $queries[$priority][] = $query;
							  $query = '';
						  }
					  } else {
						  $query .= $line;
					  }
				  }
			  }

			  ksort($queries);

			  foreach ($queries as $priority=>$to_run) {
				  foreach ($to_run as $i=>$sql) {
					  mysql_query($sql);
				  }
			  }
		  }
	  }
  }
  
}
